package com.rjs.serialization;

import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class XmlInJdkSerializer implements ISerializer {

	public byte[] serialize(Object obj) throws IOException {
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		XMLEncoder xmlEncoder = new XMLEncoder(byteArrayOutputStream);
		xmlEncoder.writeObject(obj);
		xmlEncoder.close();
		return byteArrayOutputStream.toByteArray();
	}

	@SuppressWarnings("unchecked")
	public <T> T deserialize(byte[] buf, Class<T> clzz) throws IOException, ClassNotFoundException {
		XMLDecoder xmlDecoder = new XMLDecoder(new ByteArrayInputStream(buf));
		T readObject = (T)xmlDecoder.readObject();
		xmlDecoder.close();
		return readObject;
	}

}
